<template>
  <div class="global-box">
    <a-card :body-style="{ padding: '24px' }" :bordered="false">
      <div class="form-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="6" :sm="24">
              <a-form-item label="课程目录">
                <a-cascader
                  :field-names="{ label: 'value', value: 'id', children: 'children' }"
                  change-on-select
                  :options="directoryOptions"
                  :load-data="loadData"
                  placeholder="请选择课程目录"
                  v-model="queryParam.directory"
                  @change="getType"
                />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="课程ID">
                <a-input v-model="queryParam.id" placeholder="请输入课程ID" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="课程类型">
                <a-select v-model="queryParam.type" placeholder="请选择课程类型">
                  <a-select-option
                    :key="item.classTypeId"
                    :value="item.classTypeId"
                    v-for="item in typeList"
                  >
                    {{ item.classTypeName }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="含有课件年份">
                <a-select
                  v-model="queryParam.years"
                  mode="multiple"
                  placeholder="请选择含有课件年份"
                >
                  <a-select-option v-for="item in yearList" :value="item" :key="item">{{
                    item
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="24" :sm="24">
              <span class="table-page-search-submitButtons" style="float: right">
                <a-button type="primary" @click="search">筛选</a-button>
                <a-button style="margin-left: 8px" @click="reset">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <div class="table-wrapper">
        <a-table
          :row-selection="rowSelection"
          :columns="columns"
          :data-source="data"
          :pagination="pagination"
          :rowKey="record => record.courseId"
        >
          <span slot="action" slot-scope="text, record">
            <template>
              <a-button
                type="link"
                @click="handleCopyVideo(record)"
                :disabled="record.years === '无课件' || record.isCourse"
                >复制课件</a-button
              >
            </template>
          </span>
        </a-table>
        <div class="table-foot" style="text-align: center" v-if="data.length > 0">
          <a-button type="primary" @click="handleCopyVideo()">复制课程下课件</a-button>
        </div>
      </div>
      <a-modal
        :title="courseStatusTitle"
        :visible="courseStatusVisible"
        :confirm-loading="courseStatusLoading"
        @ok="handleCopyOk"
        @cancel="handleCopyCancel"
        okText="复制"
        cancelText="取消"
        width="30%"
      >
        <a-form-model
          ref="ruleForm"
          :model="form"
          :rules="rules"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
        >
          <a-form-model-item label="课件年份" prop="courseYear">
            <a-select v-model="form.courseYear" mode="multiple" placeholder="请选择课件年份">
              <a-select-option v-for="item in yearListModel" :value="item" :key="item">{{
                item
              }}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-form-model>
      </a-modal>
    </a-card>
  </div>
</template>

<script>
import { directory, type, copyList, years, courseware } from '@/api/product/course'
const columns = [
  {
    title: '课程ID',
    dataIndex: 'courseId',
    align: 'center'
  },
  {
    title: '课程名称',
    dataIndex: 'courseName',
    align: 'center'
  },
  {
    title: '课程类型',
    dataIndex: 'courseTypeName',
    align: 'center'
  },
  {
    title: '含有课件年份',
    dataIndex: 'years',
    align: 'center'
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' },
    align: 'center'
  }
]
export default {
  data () {
    return {
      queryParam: {
        directory: [],
        id: '',
        type: undefined,
        years: []
      },
      yearList: [],
      columns,
      data: [],
      selectedRowKeys: [],
      directoryOptions: [],
      pagination: {
        current: 1,
        defaultCurrent: 1, // 默认当前页数
        defaultPageSize: 10, // 默认当前页显示数据的大小
        total: 0, // 总数，必须先有
        showSizeChanger: true,
        showQuickJumper: true,
        onShowSizeChange: (current, pageSize) => {
          this.pagination.current = 1
          this.pagination.defaultCurrent = 1
          this.pagination.defaultPageSize = pageSize
          this.getData()
        },
        // 改变每页数量时更新显示
        onChange: (current, size) => {
          this.pagination.current = current
          this.pagination.defaultCurrent = current
          this.pagination.defaultPageSize = size
          this.getData()
        }
      },
      courseStatusVisible: false,
      courseStatusLoading: false,
      courseStatusTitle: '',
      form: {
        courseYear: []
      },
      rules: {
        courseYear: [{ required: true, message: '请选择课件年份', trigger: 'change' }]
      },
      labelCol: { span: 5 },
      wrapperCol: { span: 14 },
      typeList: [],
      courseId: '',
      tableRow: '',
      yearListModel: []
    }
  },
  computed: {
    // 表格全选
    rowSelection () {
      const that = this
      return {
        onChange: (selectedRowKeys, selectedRows) => {
          that.selectedRowKeys = selectedRowKeys
        },
        getCheckboxProps: (record) => ({
          props: {
            disabled: record.years === '无课件'
          }
        })
      }
    }
  },
  mounted () {
    this.getDirectory()
    this.getYears()
    if (this.$route.params.courseId && this.$route.params.courseId !== '') {
      this.courseId = this.$route.params.courseId
      this.getData()
    }
  },
  methods: {
    // 获取课程列表数据
    getData () {
      const data = {
        classId: this.courseId,
        currentPage: this.pagination.defaultCurrent,
        pageSize: this.pagination.defaultPageSize
      }
      if (this.queryParam.type !== '') {
        data.courseTypeId = this.queryParam.type
      }
      if (this.queryParam.id !== '') {
        data.courseId = this.queryParam.id
      }
      if (this.queryParam.years.length > 0) {
        data.years = this.queryParam.years
      }
      if (this.queryParam.directory[0]) {
        data.directoryId = this.queryParam.directory[0]
      }
      if (this.queryParam.directory[1]) {
        data.examId = this.queryParam.directory[1]
      }
      if (this.queryParam.directory[2]) {
        data.subjectId = this.queryParam.directory[2]
      }
      if (this.queryParam.directory[3]) {
        data.fourExamId = this.queryParam.directory[3]
      }
      if (this.queryParam.directory[4]) {
        data.fiveExamId = this.queryParam.directory[4]
      }
      if (this.queryParam.directory[5]) {
        data.sixExamId = this.queryParam.directory[5]
      }
      copyList(data).then(res => {
        if (res.code === '1') {
          this.pagination.total = res.data.totalSize
          this.data = res.data.rows
        } else {
          this.$message.error(res.msg)
        }
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    // 表格复制课件
    handleCopyVideo (row) {
      if (!row) {
        if (this.selectedRowKeys.length > 0) {
          this.courseStatusTitle = `复制课程下课件（已选课程${this.selectedRowKeys.length}个）`
          this.courseStatusVisible = true
        } else {
          this.$message.error('请选择复制课程下课件！')
        }
      } else {
        this.yearListModel = row.yearList
        this.tableRow = row
        this.courseStatusTitle = '复制课件'
        this.courseStatusVisible = true
      }
    },
    // 复制课件确定
    handleCopyOk () {
      const data = {
        classId: this.courseId,
        years: this.form.courseYear
      }
      if (this.tableRow !== '') {
        data.courseIds = String(this.tableRow.courseId).split()
      } else {
        data.courseIds = this.selectedRowKeys
      }
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          courseware(data).then(res => {
            if (res.code === '1') {
              this.form.courseYear = []
              this.courseStatusVisible = false
              this.$message.success(res.msg)
            } else {
              this.$message.error(res.msg)
            }
          }).catch(err => {
            this.$message.error(err.msg)
          })
        } else {
          return false
        }
      })
    },
    // 复制课件取消
    handleCopyCancel () {
      this.form.courseYear = []
      this.courseStatusVisible = false
    },
    // 筛选
    search () {
      this.getData()
    },
    // 重置
    reset () {
      this.queryParam = {
        directory: [],
        id: '',
        type: undefined,
        years: []
      }
      this.selectedRowKeys = []
      this.pagination.current = 1
      this.pagination.defaultCurrent = 1
      this.getData()
    },
    // 获取含有课件年份
    getYears () {
      years({}).then(res => {
        if (res.code === '1') {
          this.yearList = res.data
        } else {
          this.$message.error(res.msg)
        }
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    // 获取课程目录
    getDirectory () {
      const data = {
        type: 0,
        directoryLevel: 1
      }
      directory(data).then(res => {
        if (res.code === '1') {
          res.data.forEach(item => {
            item.isLeaf = false
          })
          this.directoryOptions = res.data
        }
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    // 课程目录二级-六级
    loadData (selectedOptions) {
      const targetOption = selectedOptions[selectedOptions.length - 1]
      const data = {
        type: 1,
        parentId: targetOption.id,
        directoryLevel: 2
      }
      targetOption.loading = true
      directory(data).then(res => {
        if (res.code === '1') {
          if (res.data.length > 0) {
            res.data.forEach(item => {
              item.isLeaf = false
            })
            targetOption.loading = false
            targetOption.children = [...res.data]
          } else {
            targetOption.loading = false
            this.$message.error('暂无更多数据')
          }
        } else {
          targetOption.loading = false
          this.$message.error(res.msg)
        }
        this.directoryOptions = [...this.directoryOptions]
      }).catch(err => {
        this.$message.error(err.msg)
        targetOption.loading = false
      })
    },
    // 获取课程类型
    getType () {
      if (this.queryParam.directory.length === 0) {
        this.typeList = []
        this.queryParam.type = undefined
        return false
      }
      if (!this.queryParam.directory[1]) {
        return false
      }
      if (this.oldExamId === this.queryParam.directory[1]) {
        return false
      }
      const data = {
        examId: this.queryParam.directory[1]
      }
      type(data).then(res => {
        if (res.code === '1') {
          this.typeList = res.data
          this.queryParam.type = undefined
          this.oldExamId = this.queryParam.directory[1]
        } else {
          this.$message.error(res.msg)
        }
      }).catch(err => {
        this.$message.error(err.msg)
      })
    }
  }
}
</script>
<style lang="less" scoped>
.form-status-tip {
  text-align: center;
  color: #999;
}
</style>
